import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { gql, useQuery } from '@apollo/client';

import Loading from '@kuiper-components/loading';
import * as echarts from 'echarts';
import dayjs from 'dayjs';
import ECharts from '@kuiper-components/echarts';
// import Empty from '../../../../components/empty/EmptyData';
import { datetime } from '../../../../../common/formatter';

import s from './style.module.css';
import RadioButton from '../../../../components/RadioButton';
import ChartTitle from '../../../../components/ChartTitle';

const LEVEL_MAP = { all: '全部', critical: '严重', high: '高危', medium: '中危', low: '低危' };

const numFormat = function (num) {
	try {
		return new Intl.NumberFormat('en-US').format(num);
	} catch {
		return num.toLocaleString('en-US')
	}
}

const emptyLineData = [];
for (let i = 7; i >= 1; i--) {
	emptyLineData.push([
		dayjs().subtract(i, 'days').startOf('day').toDate(),
		0,
		0,
		0,
		0,
		0,
	]);
}
export default function VulTrend({
	className,
	resultNumbers,
	dateRask,
	detectTime,
	jobId,
}) {
	const [level, setLevel] = React.useState('all');
	const [myChart, setChart] = React.useState(undefined);
	const defaultList = [...resultNumbers]
		.map(
			({
				datetime,
				warnCount,
				highWarnCount,
				mediumWarnCount,
				lowWarnCount,
				criticalWarnCount
			}) => ({
				datetime: new Date(datetime),
				warnCount,
				criticalWarnCount,
				highWarnCount,
				mediumWarnCount,
				lowWarnCount
			})
		)
		.reverse();
	const highLightIdx =
		detectTime === 'last' ? defaultList.length - 1 : defaultList.length - 2;

	let lineData;
	if (level === 'all') {
		lineData = defaultList.map(item => {
			return [
				item.datetime,
				item.warnCount,
				item.criticalWarnCount,
				item.highWarnCount,
				item.mediumWarnCount,
				item.lowWarnCount
			];
		});
	} else if (level === 'critical') {
		lineData = defaultList.map(item => {
			return [item.datetime, item.criticalWarnCount];
		});
	} else if (level === 'medium') {
		lineData = defaultList.map(item => {
			return [item.datetime, item.mediumWarnCount];
		});
	} else if (level === 'high') {
		lineData = defaultList.map(item => {
			return [item.datetime, item.highWarnCount];
		});
	} else {
		lineData = defaultList.map(item => {
			return [item.datetime, item.lowWarnCount];
		});
	}
	const lineOption = {
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross',
			},
			formatter([{ seriesName, dataIndex }]) {
				const data = lineData?.[dataIndex]
				if (seriesName === '全部') {
					return `<div>
						<div style="border-bottom: 1px solid var(--color-border-2);padding: 0.5rem 1.25rem;">
							${datetime(data[0])}
						</div>
						<div>
							<div style="display: flex; padding: 0.5rem 1.25rem;">
								<div>漏洞总数</div>
								<div style="width: 3rem;text-align: right;margin-left:1.25rem;">${numFormat(
									data[1]
								)}个</div>
							</div>
							<div style="display: flex; padding: 0.5rem 1.25rem;">
								<div>严重漏洞</div>
								<div style="width: 3rem;text-align: right;margin-left:1.25rem;">${numFormat(
									data[2]
								)}个</div>
							</div>
							<div style="display: flex; padding: 0.5rem 1.25rem;">
								<div>高危漏洞</div>
								<div style="width: 3rem;text-align: right;margin-left:1.25rem;">${numFormat(
									data[3]
								)}个</div>
							</div>
							<div style="display: flex; padding: 0.5rem 1.25rem;">
								<div>中危漏洞</div>
								<div style="width: 3rem;text-align: right;margin-left:1.25rem;">${numFormat(
									data[4]
								)}个</div>
							</div>
							<div style="display: flex; padding: 0.5rem 1.25rem;">
								<div>低危漏洞</div>
								<div style="width: 3rem;text-align: right;margin-left:1.25rem;">${numFormat(
									data[5]
								)}个</div>
							</div>
						</div>
					</div>`;
				} else {
					return `<div>
					<div style="border-bottom: 1px solid var(--color-border-2);padding: 0.5rem;">
						${datetime(data[0])}
					</div>
					<div>
						<div style="display: flex; padding:0.5rem;">
							<div>${seriesName}漏洞</div>
							<div style="width: 4.25rem;text-align: right;">${numFormat(data[1])}个</div>
						</div>
					</div>
				</div>`;
				}
			},
			backgroundColor: '#fff',
			textStyle: '#696C78',
			extraCssText:
				'width: 10rem;color: var(--color-text-1);line-height:1rem;margin: 0 auto;',
		},
		axisPointer: {
			show: true,
			lineStyle: {
				width: 2,
				type: 'dotted',
				color: '#F0443C',
			},
		},
		grid: {
			left: '60',
			right: '110',
			top: '50',
			bottom: '35',
			containLabel: true
		},
		xAxis: {
			type: 'time',
			boundaryGap: false,
			splitNumber: 7,
			splitLine: { show: false },
			axisLine: { lineStyle: { color: 'transparent' }, show: false },
			axisTick: {
				show: false,
			},
			axisLabel: {
				formatter(value) {
					const date = new Date(value);
					return datetime(date, 'YYYY-MM-DD HH:mm:ss');
				},
				showMaxLabel: false,
				margin: 20,
				align: 'left',
			},
		},
		yAxis: {
			type: 'value',
			boundaryGap: false,
			axisTick: {
				show: false,
			},
			splitLine: { lineStyle: { color: '#F7F9FC' }, show: true },
			axisLine: { lineStyle: { color: 'transparent' }, show: false },
		},
		textStyle: { color: '#696C78', fontSize: 12 },
		series: [
			{
				data: [],
				name: '全部',
				type: 'line',
				smooth: true,
				smoothMonotone: 'x',
				showSymbol: false,
				symbolSize: 10,
				lineStyle: {
					color: '#F0443C',
					width: 2,
				},
				areaStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{
							offset: 0,
							color: 'rgba(240, 64, 56, 0.3646)',
						},
						{
							offset: 1,
							color: 'rgba(249, 116, 105, 0.0001)',
						},
					]),
				},
			},
		],
	};
	if (lineData.length === 0) {
		lineData = JSON.parse(JSON.stringify(emptyLineData))
		lineOption.tooltip.show = false
		lineOption.axisPointer.show = false
		lineOption.series[0].lineStyle.width = 0
		lineOption.yAxis.splitNumber = 5
		lineOption.yAxis.max = 5
		lineOption.yAxis.min = 0
	}
	lineOption.series[0].data = lineData
	lineOption.series[0].showSymbol = lineData?.length === 1
	lineOption.series[0].name = LEVEL_MAP[level];

	if (lineData.length === 0 && dateRask.dateRange) {
		lineOption.series[0].data = [
			[Date.parse(dateRask.dateRange.startTime), 0, {}],
			[Date.parse(dateRask.dateRange.endTime), 0, {}],
		];
		lineOption.series[0].lineStyle = {
			width: 0,
		};
		lineOption.axisPointer.lineStyle = {
			type: 'dotted',
			width: 0,
		};
	}
	if (highLightIdx > -1 && detectTime !== 'range') {
		lineOption.series[0].markPoint = {
			label: {
				formatter: `${detectTime === 'last' ? '最新一次监测' : '上次监测'}`,
				position: 'top',
			},
			data: [{ coord: [datetime(new Date(lineData[highLightIdx][0]), 'YYYY-MM-DD HH:mm:ss'), lineData[highLightIdx][1]] }],
			symbolSize: 24,
			itemStyle: {
				color: '#F1443C',
			},
		};
	} else {
		lineOption.series[0].markPoint = {};
	}

	const getChart = e => {
		setChart(e);
	};

	if (myChart) {
		myChart.clear()
		myChart.setOption(lineOption);
	}
	return (
		<div className={cn(className, s.trend)}>
			<div className={s.head}>
				<ChartTitle className={s.title}>漏洞监测趋势</ChartTitle>
				<div className={s.levelSelect}>
					<RadioButton
						checked={level === 'all'}
						onChecked={() => setLevel('all')}
						className={s.radio}
					>
						全部
					</RadioButton>
					<RadioButton
						checked={level === 'critical'}
						onChecked={() => setLevel('critical')}
						className={s.radio}
					>
						严重
					</RadioButton>
					<RadioButton
						checked={level === 'high'}
						onChecked={() => setLevel('high')}
						className={s.radio}
					>
						高危
					</RadioButton>
					<RadioButton
						checked={level === 'medium'}
						onChecked={() => setLevel('medium')}
						className={s.radio}
					>
						中危
					</RadioButton>
					<RadioButton
						checked={level === 'low'}
						onChecked={() => setLevel('low')}
						className={s.radio}
					>
						低危
					</RadioButton>
				</div>
			</div>
			<ECharts className={s.chart} option={lineOption} getInstance={getChart} />
		</div>
	);
}

VulTrend.propTypes = {
	className: PropTypes.string,
	resultNumbers: PropTypes.arrayOf(
		PropTypes.shape({
			warnCount: PropTypes.number,
			highWarnCount: PropTypes.number,
			mediumWarnCount: PropTypes.number,
			lowWarnCount: PropTypes.number,
			datetime: PropTypes.date,
		})
	),
	dateRask: PropTypes.object,
	detectTime: PropTypes.string,
	jobId: PropTypes.string,
};

VulTrend.defaultProps = {
	className: s.vulTrend,
};
